package edu.ou.herbarium.threads2;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.Socket;

import edu.ou.herbarium.sharedata.ErrorData;
import edu.ou.herbarium.sharedata.ShareData2;
public class ClientThread2 extends Thread{

	private Socket connectionSocket = null;
//	private ShareData1 s1;
	private ShareData2 s2;
	private ErrorData de;
	private int clientId;
	private int spanCounter = 0;
	
	public ClientThread2(ShareData2 s2, Socket socket, ErrorData de, Integer clientId) {
		this.connectionSocket = socket;
		this.s2 = s2;
		this.de = de;
		this.clientId = clientId;
	}
	
	public void run(){
		String clientSentence;
		try {
			BufferedReader inFromClient = new BufferedReader(
					new InputStreamReader(connectionSocket.getInputStream()));
			DataOutputStream outToClient = new DataOutputStream(
					connectionSocket.getOutputStream());
			System.out.println("client2 started...");
			while (true) {
				System.out.println("waiting...");
				String fileName = s2.getShareData();
				System.out.println("file name = "+fileName);
				File file = new File(fileName);
				if(file.exists()==false)
					de.setShareData("ERROR_FILE_0::Request file \""+ fileName +"\" not exist! ");
//					outToClient.writeChars("0000000100000000");
				else{
					String length = file.length()+"";
					int siz = length.length();
					if(siz<8){
						for(int i=0;i<8-siz;i++){
							length = "0"+length;
						}
					}
					System.out.println("00000001"+length);
					outToClient.writeChars("00000001"+length);
					String resp = inFromClient.readLine();
					System.out.println(resp);
					RandomAccessFile f = new RandomAccessFile(fileName, "r");
					byte[] b = new byte[(int)f.length()];
					f.read(b);
					outToClient.write(b);
					resp = inFromClient.readLine();
					System.out.println(resp);
				}
				
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
